<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Activities</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="./EldercareMasterPage/_finalstyle.css" rel="stylesheet" />
	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="./css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
    <link rel="stylesheet" type="text/css" href="./jquery/easyui.css">
    <link rel="stylesheet" type="text/css" href="./jquery/icon.css">   
</head>
<?php
	define('CONFIG_FILE',true);
	include './config.php';
	define('DB_FILE',true);

	session_start();
	if (empty($_SESSION["username"])||empty($_SESSION["userType"])) {
		Header("Location: ./Index.php");
		exit();
	}else{
		$userType = $_SESSION["userType"];
	}
	if($userType=="Therapy Assistant"){
		$url="./Index.php";
		include_once './Tool/Common/Redirect.php';
		exit();
	}

	// set timeout period in seconds
	$inactive = 7200;
	// check to see if $_SESSION['timeout'] is set
	if (isset($_SESSION["timeout"])) {
		$session_life = time() - $_SESSION["timeout"];
		if ($session_life > $inactive) {
			session_destroy();
			Header("Location: Timeout.php");
		}
	}
	$_SESSION["timeout"] = time();
?>
<body>
    <div class="banner">
	</div>
    <div id="main">
        <div class="left-wrapper">
            <div class="logo">
                <img src="images/eldercare.gif" alt="logo" width="240px" />
            </div>
			<div class="menu-wrapper">
				<div id="cssmenu">
					<?php
						if ($userType == "Therapy Assistant") {
							include_once('./Sidebar/_SidebarTA.php');
						} else if ($userType == "Centre Manager") {
							include_once('./Sidebar/_SidebarCM.php');
						} else {
							include_once('./Sidebar/_SidebarSA.php');
						}
					?>
				</div>
			</div>
		</div>
		<div id="content">
			<div class="content2">
				<b style="float:right; margin: 0px 0 0 0">  
					<?php
						if (!empty($_SESSION["centreName"])) {
							$Username = $_SESSION["username"];
							$centreName = $_SESSION["centreName"];
							echo "Welcome, " . $Username . " ! " . $centreName . " Branch";
						} else {
							$Username = $_SESSION["username"];
							echo "Welcome, " . $Username;
						}
					?>
					<input type="submit" class="btn btn-danger" value="Logout" onclick="parent.location = 'logout.php'">
				</b>
				</p>
                <br>
				<div style="float:center">
				<br>
				<h3>Activities</h3>
				<br>
				<table id="dg" title="Activities" class="easyui-datagrid" style="width:auto;height:350px; "
					   url="CRUDAct/get_act.php"
					   toolbar="#toolbar" pagination="true"
					   rownumbers="true" fitColumns="true" singleSelect="true">
					<thead>
						<tr>
							<th field="ActivityName" width="50" sortable="true">Activity Name</th>
							<th field="Category" width="50" sortable="true">Category</th>
							<th field="CentreName" width="50" sortable="true">Centre Name</th>

					<tbody style="display:none">
					<th field="ActivityId" width ="50">Activity Id</th>
					</tr>
					</thead>
				</table>
				<div id="toolbar">
					<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newAct();">New Activity</a>
					<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editAct();">Edit Activity</a>
					<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeAct();">Remove Activity</a>
					<input id="searchid" name="searchid" type="text" style="border-radius:25px">  
					<a href="#" class="easyui-linkbutton" iconCls="icon-search" onClick="getActivity();">Search</a>
					<a href="#" class="easyui-linkbutton" onClick="findAll();">All</a>
				</div>

				<!-- Insert Dialog and Form -->
				<div>
					<div id="insertdlg" class="easyui-dialog" style="width:400px;height:250px;padding:10px 20px;left:500px;top:250px;"
						 closed="true" buttons="#insertdlg-buttons">
						<div class="ftitle">Activity Information</div>
						<p></p>
						<form id="insertform" method="post" novalidate>

							<div class="fitem">
								<label>Activity Name: </label>
								<input id="InsertActivityName" name="InsertActivityName" class="easyui-validatebox" required="true"style="width:155px" height='auto'>
							</div>
							<p></p>
							<div class="fitem">
								<label>Category: </label>
								<select id="InsertCategory" name="InsertCategory"required ="true" class="easyui-combobox"style="width:155" height='auto'>
									<?php
										require_once './Tool/DB/SqlDBManager.class.php';
										$sqlDBManager = new SqlDBManager();
										$sql="Select DISTINCT Category FROM activity";
										$res=$sqlDBManager->queryRows($sql);
										if(!empty($res)){
											for($i=0;$i<count($res);$i++){
												echo "<option value=\"".$res[$i]['Category']."\">".$res[$i]['Category']."</option>";				
											}
										}					
									?>
								 </select>
							</div>
							<p></p>
							<div class="fitem">				
								<?php
								 	if($userType!="System Admin"){
										if (!empty($_SESSION["centreName"])) {
											$centreName = $_SESSION["centreName"];
											echo "<label>Centre Name: ".$centreName."</label>";
											echo "<input type=\"hidden\" id=\"InsertCentreName\" name=\"InsertCentreName\" value=\"".$centreName."\"/>";
										}
									}else{
										echo "<label>Centre Name:</label>";
										echo "<select id=\"InsertCentreName\" name=\"InsertCentreName\" class=\"easyui-combobox\"style=\"width:155\" height=\"auto\">";						
										$sqlDBManager = new SqlDBManager();
										$sql="Select CentreId, CentreName FROM centre";
										$res=$sqlDBManager->queryRows($sql);
										if(!empty($res)){
											for($i=0;$i<count($res);$i++){
												echo "<option value='".$res[$i]['CentreName']."'>".$res[$i]['CentreName']."</option>";
											}
										}									
										echo "</select>";
									}		
								?>
							</div>
						</form>
					</div>
					<div id="insertdlg-buttons">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveAct();">Save</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="insertCancel();">Cancel</a>
					</div>
				</div>

				<!-- Update Dialog and Form -->
				<div>
					<div id="updatedlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px;left:500px;top:250px;"
						 closed="true" buttons="#updatedlg-buttons">
						<div class="ftitle">Activity Information</div>
						<p></p>
						<form id="updateform" method="post" novalidate>
							<div class="fitem">
								<input id="UpdateActivityId" name="ActivityId" type="hidden" class="easyui-validatebox">
							</div> <div class="fitem">
								<label>Activity Name: </label>
								<input id="UpdateActivityName"  name="ActivityName" class="easyui-validatebox" required="true"style="width:155px" height='auto'>
							</div>
							<p></p>
							 <div class="fitem">
								<label>Category: </label>
								<select name="Category"required ="true" class="easyui-combobox"style="width:155" height='auto'>
									<?php
										//****************************************//
										//****************************************//
										require_once './Tool/DB/SqlDBManager.class.php';
										$sqlDBManager = new SqlDBManager();
										$sql="Select DISTINCT Category FROM activity";
										$res=$sqlDBManager->queryRows($sql);
										if(!empty($res)){
											for($i=0;$i<count($res);$i++){
												echo "<option value=\"".$res[$i]['Category']."\">".$res[$i]['Category']."</option>";				
											}
										}					
									?>
								</select>
							</div>
							<p></p>
							<div class="fitem">				
								<?php
									if($userType!="System Admin"){
										if (!empty($_SESSION["centreName"])) {
											$centreName = $_SESSION["centreName"];
											echo "<label>Centre Name: ".$centreName."</label>";
											echo "<input type=\"hidden\" id=\"CentreName\" name=\"CentreName\" value=\"".$centreName."\"/>";
										}
									}else{
										echo "<label>Centre Name:</label>";
										echo "<select id=\"CentreName\" name=\"CentreName\" class=\"easyui-combobox\"style=\"width:155\" height=\"auto\">";						
										$sqlDBManager = new SqlDBManager();
										$sql="Select CentreId, CentreName FROM centre";
										$res=$sqlDBManager->queryRows($sql);
										if(!empty($res)){
											for($i=0;$i<count($res);$i++){
												echo "<option value='".$res[$i]['CentreName']."'>".$res[$i]['CentreName']."</option>";
											}
										}									
										echo "</select>";
									}			
								?>
							</div>
						</form>
					</div>

					<div id="updatedlg-buttons">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="updateAct();">Save</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#updatedlg').dialog('close');">Cancel</a>
					</div>
				</div>           	
				</div>
				<div class="clear"></div>
            </div>
		</div>
	</div>

	<div id="footer">&copy; 2013 MP22 IIT-IT Temasek Polytechnic</div>
	
</body>
<script type="text/javascript" src="./jquery/jquery-1.6.min.js"></script>
<script type="text/javascript" src="./jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="./jquery/jquery.easyui.min.js"></script>
<script type="text/javascript">
	var url;
	function newAct() {
		$('#insertdlg').dialog('open').dialog('setTitle', 'New Activity');
	}

	function saveAct() {
		$('#insertform').form('submit', {
			onSubmit: function() {
				$(this).form('validate');
				//validate input	
				var flagActivityName=0;
				var flagCategory=0;
				var flagCentreName=0;
				$.ajax({
					async : false,
					type : "POST",
					url : "./CRUDAct/validateInsert.php", //the page/method you wanna validate
					data : {
						InsertActivityName: $("#InsertActivityName").val(),
						InsertCategory: $('[name="InsertCategory"]').val(),
						InsertCentreName:$('[name="InsertCentreName"]').val(),
					},
					success : function(data) {
						var data = JSON.parse(data);
						flagActivityName=data.flagActivityName;
						flagCategory=data.flagCategory;
						flagCentreName=data.flagCentreName;
					}
				});
				if(flagActivityName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Activity Name. Activity Name cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCategory==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Category Type. Category Type cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCentreName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Centre Name. Centre Name cannot contain any special characters except brackets.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else{
					return $(this).form('validate');	
				}
			},
			url: 'CRUDAct/save_act.php',
			success: function(result) {
				var result = eval('(' + result + ')');
				if (result.success) {
					$('#insertform').find('input[name="InsertActivityName"]').val('');
					$('#insertdlg').dialog('close');// close the dialog
					$('#dg').datagrid('reload');
						// reload the user data
				} else {
					$.messager.show({
						title: 'System Error',
						msg: result.msg,
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
				}
			}
		});
	}

	function editAct() {
		var row = $('#dg').datagrid('getSelected');
		if (row) {
			$('#updatedlg').dialog('open').dialog('setTitle', 'Edit Activity');
			$('#updateform').form('load', row);
		}
	}

	function updateAct() {
		$('#updateform').form('submit', {
			onSubmit: function() {
				$(this).form('validate');
				//validate input
				var flagActivityId=0;	
				var flagActivityName=0;
				var flagCategory=0;
				var flagCentreName=0;
				$.ajax({
					async : false,
					type : "POST",
					url : "./CRUDAct/validateUpdate.php", //the page/method you wanna validate
					data : {
						UpdateActivityId:$("#UpdateActivityId").val(),
						UpdateActivityName: $("#UpdateActivityName").val(),
						UpdateCategory: $('[name="Category"]').val(),
						UpdateCentreName:$('[name="CentreName"]').val(),
					},
					success : function(data) {
						var data = JSON.parse(data);
						flagActivityId=data.flagActivityId;
						flagActivityName=data.flagActivityName;
						flagCategory=data.flagCategory;
						flagCentreName=data.flagCentreName;
					}
				});
				if(flagActivityId==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Activity ID. Activity ID cannot contain any letters and special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagActivityName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Activity Name. Activity Name cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCategory==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Category Type. Category Type cannot contain any special characters.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else if(flagCentreName==0){
					$.messager.show({
						title: 'Error',
						msg: 'Invalid Centre Name. Centre Name cannot contain any special characters except brackets.',
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
					die; 
				}else{
					return $(this).form('validate');	
				}
			},
			url: 'CRUDAct/update_act.php',
			success: function(result) {
				var result = eval('(' + result + ')');
				if (result.success) {
					$('#updatedlg').dialog('close');		// close the dialog
					$('#dg').datagrid('reload');	// reload the user data
				} else {
					$.messager.show({
						title: 'Error',
						msg: result.msg,
						showType:'fade',
						style:{
		                    right:'',
                    		bottom:''
		                }
					});
				}
			}
		});
	}

	function removeAct() {
		var row = $('#dg').datagrid('getSelected');
		if (row) {
			$.messager.confirm('Confirm Delete Activity', 'Are you sure you want to remove this activities?', function(r) {
				if (r) {
					//validate Activity Id
					var check = 0;
					$.ajax({
						async : false,
						type : "POST",
						url : "./CRUDAct/validateRemove.php", //the page/method you wanna validate
						data: {
							ActivityId: row.ActivityId
						},
						success : function(data) {
							check=data;
						}
					});
					if(check==0){
						$.messager.show({
							title: 'Error',
							msg: 'Invalid Activity ID to remove.',
							showType:'fade',
							style:{
			                    right:'',
                    			bottom:''
			                }
						});
					}else{
						$.post('./CRUDAct/remove_act.php', {ActivityId: row.ActivityId}, function(result) {
							if (result.success) {
								$('#dg').datagrid('reload');	// reload the user data
							} else {
								$.messager.show({// show error message
									title: 'Error',
									msg: result.msg,
									showType:'fade',
					            	style:{
					                    right:'',
					                    bottom:''
					                }
								});
							}
						}, 'json');
					}
				}
			});
		}
	}
	function getActivity() {
        //validate search input    
        var check = 0;
        $.ajax({
            async : false,
            type : "POST",
            url : "./CRUDAct/validateSearch.php", //the page/method you wanna validate
            data: "searchid=" + $("#searchid").val(),
            success : function(data) {
                check=data;
            }
        });
        if(check==0){
            $.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input. Search Input cannot contain any special characters except brackets, dashes and colons.',
            	showType:'fade',
            	style:{
                    right:'',
                    bottom:''
                }
            });
        }else{
            $('#dg').datagrid('load', {
                searchid: $('#searchid').val()
            }); 
        }
	}

	function findAll() {
		$('#dg').datagrid('load', {
		
		});
	}

	function insertCancel(){
		$('#insertform').find('input[name="InsertActivityName"]').val('');
		$('#insertdlg').dialog('close');
	}

	$(function(){ 
        $("#InsertCategory").next().find("input.validatebox-text").attr("readonly","readonly");  
        $("#UpdateCategory").next().find("input.validatebox-text").attr("readonly","readonly");     
    });
</script>
</html>
